package com.wyzt.auth.service;

import com.wyzt.auth.client.UserClient;
import com.wyzt.auth.config.JwtProperties;
import com.wyzt.auth.entiy.UserInfo;
import com.wyzt.auth.utils.JwtUtils;
import com.wyzt.common.enums.ExceptionEnum;
import com.wyzt.common.exception.WyztException;
import com.wyzt.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties(JwtProperties.class)
@Slf4j
public class AuthService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties jwtProp;

    public String login(String username, String password) {
        //校验用户名和密码
        User user = userClient.queryUserByUsernameAndPassword(username, password);
        if (user == null) {
            throw new WyztException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //生成token
        try {
            String token = JwtUtils.generateToken(
                    new UserInfo(user.getId(), username),
                    jwtProp.getPrivateKey(),
                    jwtProp.getExpire());
            return token;
        } catch (Exception e) {
            log.error("[授权中心]生成token失败，{}", username);
            throw new WyztException(ExceptionEnum.CREATE_TOKEN_ERROR);
        }
    }
}
